﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using Moq;
using System.Net;
using System.Web.Mvc;
using System.Web.Routing;

namespace WhittleList.Tests.Mocks
{
    public class FakeHttpContext : Mock<HttpContextBase>
    {
        public FakeHttpContext()
        {
            Request = new Mock<HttpRequestBase>();
            Response = new Mock<HttpResponseBase>();
            Session = new Mock<HttpSessionStateBase>();
            Server = new Mock<HttpServerUtilityBase>();
            User = new Mock<IPrincipal>();
            Identity = new Mock<IIdentity>();
            RequestHeaders = new WebHeaderCollection();

            this.Setup(x => x.Request).Returns(Request.Object);
            Request.Setup(x => x.Headers).Returns(RequestHeaders);

            this.Setup(x => x.Response).Returns(Response.Object);
            this.Setup(x => x.Session).Returns(Session.Object);
            this.Setup(x => x.Server).Returns(Server.Object);
            this.Setup(x => x.User).Returns(User.Object);
            
            User.Setup(x => x.Identity).Returns(Identity.Object);
        }

        public Mock<HttpRequestBase> Request { get; private set; }
        public Mock<HttpResponseBase> Response { get; private set; }
        public Mock<HttpSessionStateBase> Session { get; private set; }
        public Mock<HttpServerUtilityBase> Server { get; private set; }
        public Mock<IPrincipal> User { get; private set; }
        public Mock<IIdentity> Identity { get; private set; }

        public WebHeaderCollection RequestHeaders { get; private set; }

        /// <summary>
        /// Sets or removes the Ajax X-Requested-With="XMLHttpRequest" header
        /// </summary>
        /// <param name="value"></param>
        public void SetAjax(bool value)
        {
            if (value)
            {
                RequestHeaders["X-Requested-With"] = "XMLHttpRequest";
            }
            else
            {
                RequestHeaders.Remove("X-Requested-With");
            }
        }

        public void SetRequestType(HttpVerbs requestType)
        {
            Request.Setup(x => x.RequestType).Returns(requestType.ToString().ToUpper());
        }

        public void AttachToControllerContext(Controller controller)
        {
            AttachToControllerContext(controller, new RouteData());
        }

        public void AttachToControllerContext(Controller controller, RouteData routeData)
        {
            controller.ControllerContext = new ControllerContext(this.Object, routeData, controller);
        }
    }
}
